<template>
  <div>
    <!-- 搜索 -->
    <search-bar @onSearch="onSearch" />
    <div style="display: flex;">
        <!-- 单个新增商品 -->
        <el-button @click="$router.push('/itemAdd')" type="primary" style="background:darkgreen;margin:10px 0">单个新增商品</el-button>
        <!-- 批量新增商品 -->
        <el-upload
        v-model:file-list="fileList"
        action="#"
        multiple
        :before-upload="pluses"
      >
          <el-button type="primary" style="background:darkgreen;margin:10px 8px">批量新增商品</el-button>
        </el-upload>
        <!-- 下载Excel模板 -->
        <el-button @click="xlsxExport" type="primary" style="background:darkgreen;margin:10px 0">下载Excel模板</el-button>
    </div>
    <!-- table数据表格渲染 -->
    <el-table :data="items" style="width: 100%">
    <!-- 商品名称     sortable是否有排序 -->
    <el-table-column prop="itemName" label="商品名称" width="120px" sortable/>
    <!-- 售价 -->
    <el-table-column prop="price" label="售价" width="90px" sortable>
      <template #default="{ row }">
          <el-tag :color="row.price > 1000 ? 'red' : 'green'">{{ row.price }}</el-tag>
        </template>
    </el-table-column>
    <!-- 销量 -->
    <el-table-column prop="sale" label="销量" width="90px" sortable>
      <template #default="{ row }">
          <el-tag :color="row.sale > 40000 ? 'red' : 'green'">{{ row.sale }}</el-tag>
        </template>
    </el-table-column>
    <!-- 在售/下架 -->
    <el-table-column prop="onsale" label="在售/下架" width="120px" sortable>
        <template #default="{ row }">
          <div>
            <el-switch
              v-model="row.onsale" inline-prompt active-text="在售"
              @change="switch_onsale(row.id, row.onsale)"
              inactive-text="下架" />
          </div>
        </template>
    </el-table-column>
    <!-- 商品展示图 -->
    <el-table-column prop="thumb" label="商品展示图" width="120px">
        <template #default="{ row }">
          <div>
            <img :src="row.thumb" alt="">
          </div>
        </template>
      </el-table-column>
      <!-- 创建时间 -->
    <el-table-column prop="createAt" label="创建时间" width="120px" sortable/>
      <!-- 商品描述 -->
      <el-table-column prop="desc" label="商品描述" width="auto">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" placement="bottom">
            <template #content>
              <div style="width: 300px">
                {{ row.desc }}
              </div>
            </template>
            <!-- 商品数据描述 裁剪后拼接 -->
            <div>{{ row.desc.substr(0, 12) + '...' }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="auto">
        <!-- <template #default="{ row }"> -->
        <template #default="{ row }">
        <!-- 编辑商品 按钮 -->
          <el-button @click="enterChangeItem(row.id)" type="primary">编辑</el-button>
        <!-- 删除 -->
          <el-button @click="delItem(row.id)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
    style="margin: 10px 0"
    v-model:page-size="pageSize"
    v-model:current-page="page"
    layout="total, prev, pager, next, jumper"
    :page-sizes="[10]"
    :small="false"
    :disabled="disabled"
    :background="true"
    :total="total"
    />
  </div>
</template>

<script>
import SearchBar from '../../components/SearchBar.vue'
import { fetchItems, delItem, addItems } from '../../api/itemLists'
import { updateItems } from '../../api/itemUpdate'
import { read, utils, writeFileXLSX } from 'xlsx'

export default {
  name: 'itemLists',
  data () {
    return {
      searchParams: {
        key: '',
        start: '',
        end: ''
      },
      // 分页需要的参数
      page: 1,
      pageSize: 10,
      items: [],
      total: 0
    }
  },
  methods: {
    // xlsx模板下载
    xlsxExport () {
      const data = [{
        商品名: '8846',
        商品价格: '19999',
        商品描述: '描述'
      }]
      const ws = utils.json_to_sheet(data)
      const wb = utils.book_new()
      utils.book_append_sheet(wb, ws, 'Data')
      writeFileXLSX(wb, '商品excel模板.xlsx')
    },
    // 批量添加
    pluses (file) {
      const fd = new FileReader()
      fd.readAsArrayBuffer(file)
      fd.onload = () => {
        const wb = read(fd.result)
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        const data2 = data.map(item => {
          return {
            itemName: item.商品名,
            price: item.商品价格,
            desc: item.商品描述
          }
        })
        addItems({
          items: data2
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      }
      return false
    },
    // 编辑修改某一项商品
    enterChangeItem (id) {
      this.$router.push({
        path: '/ItemUpdate',
        query: {
          id
        }
      })
    },
    // 删除表格中某一项商品
    delItem (id) {
      this.$confirm('此操作会彻底删除商品,继续吗?', '删除').then(() => {
        delItem(id).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'succsee',
              message: res.data.msg
            })
            this.$router.go(0)
          }
        })
      })
    },
    // onSale状态修改
    switch_onsale (id, onsale) {
      updateItems({
        id,
        onsale
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 2000,
            onClose: () => {
              this.$router.go(0)
            }
          })
        }
      })
    },
    // 搜索
    onSearch (searchParams) {
      this.searchParams = searchParams
      this.fetchItems()
      this.$message({
        type: 'success',
        message: '搜索成功、等待搜索结果刷新'
      })
    },
    // 请求商品列表
    fetchItems () {
      fetchItems({
        ...this.searchParams,
        age: this.page,
        pageSize: this.pageSize
      }).then(res => {
        console.log(res.data.data.lists, 'table数据')
        console.log(res.data.data.total, '数据总条数')
        if (res.data.code === 200) {
          this.items = res.data.data.lists
          this.total = res.data.data.total
        }
      })
    }
  },
  watch: {
    // 监听当前页页码 和 一页多少条  再重新请求列表、渲染
    page () {
      this.fetchItems()
    },
    pageSize () {
      this.fetchItems()
    }
  },
  // 发出请求、获取数据
  created () {
    this.fetchItems()
  },
  // 子组件使用
  components: {
    SearchBar
  }
}

</script>

<style lang="scss" scoped>

</style>
